package com.mojo.collection.map;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * hashmap实现原理
 *
 * @author <a href="mailto:mojo_jj@163.com">Mojo</a>
 */
public class HashMapDemo {
    public static void main(String[] args) {
        Map<Integer, String> map = new HashMap<>(8);
        map.put(1, "mojo");
        map.put(null, "muzhe");
        map.put(null, "sd");
        System.out.println(map.remove(1));
        Set<Map.Entry<Integer, String>> entries = map.entrySet();
        for (Map.Entry<Integer, String> entry : entries) {
            Integer key = entry.getKey();
            String value = entry.getValue();
        }
        //hashMap线程不安全示例
        HashMap<Object, Object> map1 = new HashMap<>(8);
        System.out.println(tableSizeFor(11));
        System.out.println("=============================================");
        mapPut();
        System.out.println("=============================================");
        int i = -1 >>> 16;
        System.out.println(Integer.toBinaryString(-1));
        System.out.println(Integer.toBinaryString(i));
    }

    // hashMap put()示例
    private static void mapPut() {
        Map<Object, Object> map = new HashMap<>(2);
        map.put(2, "sdfa2");
        map.put(1, "sdfa1");
        map.put(4, "sdfa4");
        map.put(3, "sdfa3");
        map.put(1, "sdfa5");
        String s = map.toString();
        System.out.println(map);

    }

    private static final int tableSizeFor(int c) {
        int n = c - 1;
        n |= n >>> 1;
        n |= n >>> 2;
        n |= n >>> 4;
        n |= n >>> 8;
        n |= n >>> 16;
        return (n < 0) ? 1 : (n >= 1 << 30) ? 1 << 30 : n + 1;
    }
}
